package com.china08.yxyapi.service.sws.teaching.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.entity.mg.esbag.YxyEsbagTeachingTrack;
import com.china08.yxyapi.service.sws.teaching.EsbagTeachingStatisticsService;
import com.china08.yxyapi.util.DateUtils;
import com.google.gson.Gson;

@Service
public class EsbagTeachingStatisticsServiceImpl implements EsbagTeachingStatisticsService {

    private static final Logger LOGGER = Logger.getLogger(LecturePackStatisticsServiceImpl.class);

    @Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RestTemplate restTemplate;

    // Esbag——Class
    @Override
    public void getEsbagForClass(Integer day) throws ParseException {
        Date dayDate = DateUtils.getBeforeDay(DateUtils.formatStrDate4(day));
        Date startDate = DateUtils.getFirstDay(dayDate);
        Date endDate = DateUtils.getTimesnight(dayDate);

        Criteria criteria = Criteria.where("endDate").gte(startDate).lte(endDate);

        // 获取考试信息
        TypedAggregation<YxyEsbagTeachingTrack> aggregation = Aggregation.newAggregation(YxyEsbagTeachingTrack.class,
                Aggregation.match(criteria),
                Aggregation.group("classId")//
                        .count().as("usedCount")//
                        .first("classId").as("classId")//
                        .first("className").as("className")//
                        .first("schoolNick").as("schoolNick")//
                        .first("schoolId").as("schoolId"));

        AggregationResults<ClassPackModel> result = mongoTemplate.aggregate(aggregation, ClassPackModel.class);
        List<ClassPackModel> classEsbagModelLst = result.getMappedResults();
        List<ClassPackModel> sendDataLst = new ArrayList<ClassPackModel>();

        Integer index = 0;
        for (ClassPackModel classEsbagModel : classEsbagModelLst) {

            Criteria criteriaClass = Criteria.where("endDate").gte(startDate).lte(endDate);
            criteriaClass.and("classId").is(classEsbagModel.classId);
            criteriaClass.and("useTime").gte(300);
            Query query = new Query();
            query.addCriteria(criteriaClass);
            Long count = mongoTemplate.count(query, YxyEsbagTeachingTrack.class);
            classEsbagModel.teachingCount = count;

            sendDataLst.add(classEsbagModel);
            index++;
            if (index == 100) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Gson gson = new Gson();
                    StringBuffer objectBuffer = new StringBuffer();
                    objectBuffer.append("{");
                    objectBuffer.append("\"classPackModelLst\":" + gson.toJson(sendDataLst) + ",");
                    objectBuffer.append("\"dateTime\":" + DateUtils.formatDate4(dayDate));
                    objectBuffer.append("}");
                    HttpEntity<String> formEntity = new HttpEntity<String>(objectBuffer.toString(), headers);
                    String httpResult = restTemplate.postForObject(
                            yxyApiYxUrl + "/comm/school/sws/teaching/teachingclass/esbag", formEntity, String.class);
                    if (httpResult.contains("success")) {
                        System.out.println("getPackForClass方法执行ok");
                    }
                } catch (Exception e) {
                    LOGGER.info("getPackForClass方法执行错误：" + e.getMessage());
                }
                sendDataLst = new ArrayList<ClassPackModel>();
                index = 0;
            }
        }
        if (sendDataLst.size() > 0) {
            try {
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                Gson gson = new Gson();
                StringBuffer objectBuffer = new StringBuffer();
                objectBuffer.append("{");
                objectBuffer.append("\"classPackModelLst\":" + gson.toJson(sendDataLst) + ",");
                objectBuffer.append("\"dateTime\":" + DateUtils.formatDate4(dayDate));
                objectBuffer.append("}");
                HttpEntity<String> formEntity = new HttpEntity<String>(objectBuffer.toString(), headers);
                String httpResult = restTemplate.postForObject(
                        yxyApiYxUrl + "/comm/school/sws/teaching/teachingclass/esbag", formEntity, String.class);
                if (httpResult.contains("success")) {
                    System.out.println("getPackForClass方法执行ok");
                }
            } catch (Exception e) {
                LOGGER.info("getPackForClass方法执行错误：" + e.getMessage());
            }
        }
    }

    protected static class ClassPackModel {
        public Long usedCount;
        public Long teachingCount;

        public String classId;
        public String className;
        public String schoolId;
        public String schoolNick;
    }

    // Esbag——School
    @Override
    public void getEsbagForSchool(Integer day) throws ParseException {
        Date dayDate = DateUtils.getBeforeDay(DateUtils.formatStrDate4(day));
        Date startDate = DateUtils.getFirstDay(dayDate);
        Date endDate = DateUtils.getTimesnight(dayDate);

        Criteria criteria = Criteria.where("endDate").gte(startDate).lte(endDate);

        // 获取考试信息
        TypedAggregation<YxyEsbagTeachingTrack> aggregation = Aggregation.newAggregation(YxyEsbagTeachingTrack.class,
                Aggregation.match(criteria),
                Aggregation.group("schoolId")//
                        .count().as("usedCount")//
                        .first("schoolId").as("schoolId")//
                        .first("schoolNick").as("schoolNick"));

        AggregationResults<SchoolPackModel> result = mongoTemplate.aggregate(aggregation, SchoolPackModel.class);
        List<SchoolPackModel> schoolPackModelLst = result.getMappedResults();
        List<SchoolPackModel> sendDataLst = new ArrayList<SchoolPackModel>();

        Integer index = 0;
        for (SchoolPackModel schoolPackModel : schoolPackModelLst) {

            Criteria criteriaSchool = Criteria.where("endDate").gte(startDate).lte(endDate);
            criteriaSchool.and("schoolId").is(schoolPackModel.schoolId);
            criteriaSchool.and("useTime").gte(300);
            Query query = new Query();
            query.addCriteria(criteriaSchool);
            Long count = mongoTemplate.count(query, YxyEsbagTeachingTrack.class);
            schoolPackModel.teachingCount = count;

            sendDataLst.add(schoolPackModel);
            index++;
            if (index == 100) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Gson gson = new Gson();
                    StringBuffer objectBuffer = new StringBuffer();
                    objectBuffer.append("{");
                    objectBuffer.append("\"schoolPackModelLst\":" + gson.toJson(sendDataLst) + ",");
                    objectBuffer.append("\"dateTime\":" + DateUtils.formatDate4(dayDate));
                    objectBuffer.append("}");
                    HttpEntity<String> formEntity = new HttpEntity<String>(objectBuffer.toString(), headers);
                    String httpResult = restTemplate.postForObject(
                            yxyApiYxUrl + "/comm/school/sws/teaching/bureau/esbag", formEntity, String.class);
                    if (httpResult.contains("success")) {
                        System.out.println("getPackForSchool方法执行ok");
                    }
                } catch (Exception e) {
                    LOGGER.info("getPackForSchool方法执行错误：" + e.getMessage());
                }
                sendDataLst = new ArrayList<SchoolPackModel>();
                index = 0;
            }
        }
        if (sendDataLst.size() > 0) {
            try {
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                Gson gson = new Gson();
                StringBuffer objectBuffer = new StringBuffer();
                objectBuffer.append("{");
                objectBuffer.append("\"schoolPackModelLst\":" + gson.toJson(sendDataLst) + ",");
                objectBuffer.append("\"dateTime\":" + DateUtils.formatDate4(dayDate));
                objectBuffer.append("}");
                HttpEntity<String> formEntity = new HttpEntity<String>(objectBuffer.toString(), headers);
                String httpResult = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/sws/teaching/bureau/esbag",
                        formEntity, String.class);
                if (httpResult.contains("success")) {
                    System.out.println("getPackForSchool方法执行ok");
                }
            } catch (Exception e) {
                LOGGER.info("getPackForSchool方法执行错误：" + e.getMessage());
            }
        }
    }

    protected static class SchoolPackModel {
        public Long usedCount;
        public Long teachingCount;

        public String schoolId;
        public String schoolNick;
    }

    // Esbag——User
    @Override
    public void getEsbagForUser(Integer day) throws ParseException {
        Date dayDate = DateUtils.getBeforeDay(DateUtils.formatStrDate4(day));
        Date startDate = DateUtils.getFirstDay(dayDate);
        Date endDate = DateUtils.getTimesnight(dayDate);

        Criteria criteria = Criteria.where("endDate").gte(startDate).lte(endDate);

        // 获取考试信息
        TypedAggregation<YxyEsbagTeachingTrack> aggregation = Aggregation.newAggregation(YxyEsbagTeachingTrack.class,
                Aggregation.match(criteria),
                Aggregation.group("teacherId", "schoolId")//
                        .count().as("usedCount")//
                        .first("schoolId").as("schoolId")//
                        .first("schoolNick").as("schoolNick")//
                        .first("teacherId").as("userId"));

        AggregationResults<UserPackModel> result = mongoTemplate.aggregate(aggregation, UserPackModel.class);
        List<UserPackModel> userPackModellLst = result.getMappedResults();
        List<UserPackModel> sendDataLst = new ArrayList<UserPackModel>();

        Integer index = 0;
        for (UserPackModel userPackModel : userPackModellLst) {

            Criteria criteriaUser = Criteria.where("endDate").gte(startDate).lte(endDate);
            criteriaUser.and("schoolId").is(userPackModel.schoolId);
            criteriaUser.and("teacherId").is(userPackModel.userId);
            criteriaUser.and("useTime").gte(300);
            Query query = new Query();
            query.addCriteria(criteriaUser);
            Long count = mongoTemplate.count(query, YxyEsbagTeachingTrack.class);
            userPackModel.teachingCount = count;

            sendDataLst.add(userPackModel);
            index++;
            if (index == 100) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Gson gson = new Gson();
                    StringBuffer objectBuffer = new StringBuffer();
                    objectBuffer.append("{");
                    objectBuffer.append("\"userPackModelLst\":" + gson.toJson(sendDataLst) + ",");
                    objectBuffer.append("\"dateTime\":" + DateUtils.formatDate4(dayDate));
                    objectBuffer.append("}");
                    HttpEntity<String> formEntity = new HttpEntity<String>(objectBuffer.toString(), headers);
                    String httpResult = restTemplate.postForObject(
                            yxyApiYxUrl + "/comm/school/sws/teaching/teacher/esbag", formEntity, String.class);
                    if (httpResult.contains("success")) {
                        System.out.println("getPackForUser方法执行ok");
                    }
                } catch (Exception e) {
                    LOGGER.info("getPackForUser方法执行错误：" + e.getMessage());
                }
                sendDataLst = new ArrayList<UserPackModel>();
                index = 0;
            }
        }
        if (sendDataLst.size() > 0) {
            try {
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                Gson gson = new Gson();
                StringBuffer objectBuffer = new StringBuffer();
                objectBuffer.append("{");
                objectBuffer.append("\"userPackModelLst\":" + gson.toJson(sendDataLst) + ",");
                objectBuffer.append("\"dateTime\":" + DateUtils.formatDate4(dayDate));
                objectBuffer.append("}");
                HttpEntity<String> formEntity = new HttpEntity<String>(objectBuffer.toString(), headers);
                String httpResult = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/sws/teaching/teacher/esbag",
                        formEntity, String.class);
                if (httpResult.contains("success")) {
                    System.out.println("getPackForUser方法执行ok");
                }
            } catch (Exception e) {
                LOGGER.info("getPackForUser方法执行错误：" + e.getMessage());
            }
        }
    }

    protected static class UserPackModel {
        public Long usedCount;
        public Long teachingCount;

        public String schoolId;
        public String schoolNick;
        public String userId;
    }

}
